﻿using System.Diagnostics;
using System.IO;
using AutoBuild.Core;
using AutoBuild.Core.Framework;

namespace AutoBuild.Runner.NAntRunner
{
    public class NAntBuildRunner : AbstractBuildRunner<NAntBuildRunnerOptions>
    {
        //---- Members -----------------------------------------------------
        readonly IPathResolver _pathResolver;
        private readonly IConsole _console;
        private readonly IProcessExecutor _processExecutor;

        //---------------------------------------------------------
        public override string RunnerName
        {
            get { return "NAnt"; }
        }

        //---------------------------------------------------------
        public bool CreateNoWindow { get; set; }

        //---------------------------------------------------------
        public NAntBuildRunner(IPathResolver pathResolver, IConsole console, IProcessExecutor processExecutor)
        {
            _pathResolver = pathResolver;
            _console = console;
            _processExecutor = processExecutor;
        }

        //---------------------------------------------------------
        public override void RunBuild(AutoBuildArguments arguments)
        {
            OnBuildStarted();
            ExecuteBuildProcess(arguments);
            OnBuildCompleted();
        }

        
        //---------------------------------------------------------
        private void ExecuteBuildProcess(AutoBuildArguments autoBuildArguments)
        {
            var nantArguments = autoBuildArguments.RunnerArgument as NAntBuildRunnerOptions;
            var nantPath = _pathResolver.Resolve(nantArguments.NAntExePath);
            var buildFile = autoBuildArguments.BuildFile;

            _console.Debug("NAnt executable path, {0}".With(nantPath));

            var assembly = typeof(NAntBuildRunner).Assembly;
            var arguments =
                "-f:\"{0}\" -ext:\"{1}\" -logger:{2} -e -nologo {3}"
                    .With(
                    buildFile,
                    assembly.Location,
                    typeof(NAntBuildLogger).FullName,
                    nantArguments.NAntAdditionalArguments
                    );

            var workingDir = Path.GetDirectoryName(assembly.Location);
            _console.Debug("Running NAnt with exe: {0}; Arguments: '{1}'; Working dir: {2}".With(nantPath, arguments, workingDir));


            _processExecutor.Execute(
                new ProcessStartInfo
                    {
                        FileName = nantPath,
                        Arguments = arguments,
                        UseShellExecute = false,
                        CreateNoWindow = CreateNoWindow,
                        WorkingDirectory = workingDir
                    }
                );
        }
    }
}
